import java.sql.ResultSet;
import java.sql.SQLException;

import mysql.Mysql;

/**
 * Class Map
 */
public class Map {

	//
	// Fields
	//

	private int id;
	private Tile[][] tiles;
	private int size;

	//
	// Constructors
	//
	public Map(int size) {
		this.size = size;

		this.tiles = new Tile[size][size];

		for (int i = 0; i < this.size; i++) {
			for (int j = 0; j < this.size; j++) {
				this.tiles[i][j] = new Tile(null, "");
			}
		}
	}

	public void print() {
		System.out.print(this.size+"><");
		for (int i = 0; i < this.size; i++) {
			for (int j = 0; j < this.size; j++) {
				if (this.tiles[i][j].isEmpty() == true) {
					System.out.print("0;");
				} else {
					this.tiles[i][j].getComponent().print();
					System.out.print(";");
				}
			}
		}

	}

	//
	// Methods
	//

	public boolean isEmpty(int i, int j) {
		return this.tiles[i][j].isEmpty();
	}

	public Component getComponent(int i, int j) {
		return this.tiles[i][j].getComponent();
	}

	public boolean setComponent(Component c, int i, int j) {
		return this.tiles[i][j].setComponent(c);
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getId() {
		return this.id;
	}

	public int getSize() {
		return this.size;
	}
	
	public Tile getTileComponent(Component c) {
		for (int i = 0; i < this.size; i++) {
			for (int j = 0; j < this.size; j++) {
				if (this.tiles[i][j].isEmpty() == false) {
					if (this.tiles[i][j].getComponent().getId() == c.getId()) {
						return this.tiles[i][j];
					}
				} 
			}
		}
		
		return null;
	}

	public void loadTiles() {
		Mysql bd = new Mysql();
		String strsql = "select * from tb_tiles where map_id = " + this.id;
		
		ResultSet rs = bd.select(strsql);
		try {
			while (rs.next()) {				
				Auxiliar aux = new Auxiliar();
				Component c = aux.loadComponent(Integer.parseInt(rs.getString("component_id")));
				int i, j;
				i = Integer.parseInt(rs.getString("x"));
				j = Integer.parseInt(rs.getString("y"));
				this.tiles[i][j].setComponent(c);
				this.tiles[i][j].setId(Integer.parseInt(rs.getString("id")));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void save() {
		Mysql bd = new Mysql();
		String strsql;

		strsql = "insert into tb_maps (size) value (" + this.size + ")";
		ResultSet rs = bd.insertUpdate(strsql);
		try {
			rs.next();
			this.id = rs.getInt(1);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void saveTile(int i, int j) {
		this.tiles[i][j].save(this.id, i, j);
	}

}
